package com.qianjing.framework.security.service;

import com.qianjing.framework.security.LoginTicket;
import com.qianjing.common.constant.Constants;
import com.qianjing.framework.security.LoginUser;
import com.qianjing.project.system.domain.SysUser;
import com.qianjing.project.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Classname OAuthUserDetailsService
 * @Description 单点统一认证用户信息
 * @Created by zzy 2022年8月29日 下午3:55:54
 * @Version V1.0
 */
@Service
public class OAuthUserDetailsService implements UserDetailsService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public LoginUser loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByUserName(userName);
        return createLoginUser(user);
    }

    /**
     * <p> 更新用户信息 </p>
     * @param user
     * @param loginTicket
     * @return
     */
    public LoginUser updateSsoUser(SysUser user, LoginTicket loginTicket) {
        user.setNickName(loginTicket.getNickName());
        user.setUserName(loginTicket.getUserName());
        user.setLoginIp(loginTicket.getIp());
        user.setLoginDate(new Date());
        user.setUpdateBy(loginTicket.getUserName());
        user.setUpdateTime(new Date());
        user.setUserGuid(loginTicket.getUserGuid());
        user.setRoleIds(loginTicket.getRoleIds());
        userService.updateUser(user);
        return createLoginUser(user);
    }

    /**
     * <p> 创建用户信息 </p>
     * @param loginTicket
     * @return
     */
    public LoginUser createSsoUser(LoginTicket loginTicket) {
        SysUser user = new SysUser();
        user.setNickName(loginTicket.getNickName());
        user.setUserName(loginTicket.getUserName());
        user.setLoginIp(loginTicket.getIp());
        user.setLoginDate(new Date());
        user.setUserGuid(loginTicket.getUserGuid());
        user.setDelFlag(Constants.DB_IS_STATUS_NO);
        user.setCreateBy(loginTicket.getUserName());
        user.setCreateTime(new Date());
        user.setRoleIds(loginTicket.getRoleIds());
        userService.insertUser(user);
        return createLoginUser(user);
    }

    private LoginUser createLoginUser(SysUser user) {
        if (user != null) {
            return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
        }
        return null;
    }
}
